<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="format-detection" content="telephone=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="icon" href="/blog/blog/images/icons/favicon-16x16.png?v=2.6.2" type="image/png" sizes="16x16"><link rel="icon" href="/blog/blog/images/icons/favicon-32x32.png?v=2.6.2" type="image/png" sizes="32x32"><meta name="description" content=".back-top{position: fixed;top: 500px;height: 0px;float: right;right: 50px;} .back-top&gt;a{font-weight:bold;width: 50px;height: 50px;text-align: center;text-decoration: none;font-size: 5px;line-height:">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis学习笔记(所有代码FROM SIKI学院)">
<meta property="og:url" content="https://bruce-jj.gitee.io/blog/2021/03/11/Mybatis/index.html">
<meta property="og:site_name" content="斯人若彩虹 遇上方知有">
<meta property="og:description" content=".back-top{position: fixed;top: 500px;height: 0px;float: right;right: 50px;} .back-top&gt;a{font-weight:bold;width: 50px;height: 50px;text-align: center;text-decoration: none;font-size: 5px;line-height:">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210313165831616.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210410185916946.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20210406191232940.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2021-03-11T11:37:23.000Z">
<meta property="article:modified_time" content="2021-05-08T12:32:42.000Z">
<meta property="article:author" content="何水浪">
<meta property="article:tag" content="SSM学习笔记">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20210313165831616.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70"><title>Mybatis学习笔记(所有代码FROM SIKI学院) | 斯人若彩虹 遇上方知有</title><link ref="canonical" href="https://bruce-jj.gitee.io/blog/2021/03/11/Mybatis/"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.12.1/css/all.min.css" type="text/css"><link rel="stylesheet" href="/blog/css/index.css?v=2.6.2"><script>var Stun = window.Stun || {};
var CONFIG = {
  root: '/blog/',
  algolia: undefined,
  assistSearch: undefined,
  fontIcon: {"prompt":{"success":"fas fa-check-circle","info":"fas fa-arrow-circle-right","warning":"fas fa-exclamation-circle","error":"fas fa-times-circle"},"copyBtn":"fas fa-copy"},
  sidebar: {"offsetTop":"20px","tocMaxDepth":6},
  header: {"enable":true,"showOnPost":true,"scrollDownIcon":false},
  postWidget: {"endText":true},
  nightMode: {"enable":true},
  back2top: {"enable":true},
  codeblock: {"style":"default","highlight":"light","wordWrap":false},
  reward: false,
  fancybox: false,
  zoomImage: {"gapAside":"20px"},
  galleryWaterfall: undefined,
  lazyload: false,
  pjax: undefined,
  externalLink: {"icon":{"enable":true,"name":"fas fa-external-link-alt"}},
  shortcuts: undefined,
  prompt: {"copyButton":"复制","copySuccess":"复制成功","copyError":"复制失败"},
  sourcePath: {"js":"js","css":"css","images":"images"},
};

window.CONFIG = CONFIG;</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/blog/atom.xml" title="斯人若彩虹 遇上方知有" type="application/atom+xml">
</head><body><div class="container" id="container"><header class="header" id="header"><div class="header-inner"><nav class="header-nav header-nav--fixed"><div class="header-nav-inner"><div class="header-nav-menubtn"><i class="fas fa-bars"></i></div><div class="header-nav-menu"><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/"><span class="header-nav-menu-item__icon"><i class="fas fa-home"></i></span><span class="header-nav-menu-item__text">首页</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/archives/"><span class="header-nav-menu-item__icon"><i class="fas fa-folder-open"></i></span><span class="header-nav-menu-item__text">归档</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/categories/"><span class="header-nav-menu-item__icon"><i class="fas fa-layer-group"></i></span><span class="header-nav-menu-item__text">分类</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/tags/"><span class="header-nav-menu-item__icon"><i class="fas fa-tags"></i></span><span class="header-nav-menu-item__text">标签</span></a></div><div class="header-nav-menu-item"><a class="header-nav-menu-item__link" href="/blog/friends/"><span class="header-nav-menu-item__icon"><i class="fas fa-link"></i></span><span class="header-nav-menu-item__text">友链</span></a></div></div><div class="header-nav-search"><span class="header-nav-search__icon"><i class="fas fa-search"></i></span><span class="header-nav-search__text">搜索</span></div><div class="header-nav-mode"><div class="mode"><div class="mode-track"><span class="mode-track-moon"></span><span class="mode-track-sun"></span></div><div class="mode-thumb"></div></div></div></div></nav><div class="header-banner"><div class="header-banner-info"><div class="header-banner-info__title">斯人若彩虹 遇上方知有</div><div class="header-banner-info__subtitle"></div></div></div></div></header><main class="main" id="main"><div class="main-inner"><div class="content-wrap" id="content-wrap"><div class="content" id="content"><!-- Just used to judge whether it is an article page--><div id="is-post"></div><div class="post"><header class="post-header"><h1 class="post-title">Mybatis学习笔记(所有代码FROM SIKI学院)</h1><div class="post-meta"><span class="post-meta-item post-meta-item--createtime"><span class="post-meta-item__icon"><i class="far fa-calendar-plus"></i></span><span class="post-meta-item__info">发表于</span><span class="post-meta-item__value">2021-03-11</span></span><span class="post-meta-item post-meta-item--updatetime"><span class="post-meta-item__icon"><i class="far fa-calendar-check"></i></span><span class="post-meta-item__info">更新于</span><span class="post-meta-item__value">2021-05-08</span></span><span class="post-meta-item post-meta-item--wordcount"><span class="post-meta-item__icon"><i class="far fa-file-word"></i></span><span class="post-meta-item__info">字数统计</span><span class="post-meta-item__value">4.9k</span></span><span class="post-meta-item post-meta-item--readtime"><span class="post-meta-item__icon"><i class="far fa-clock"></i></span><span class="post-meta-item__info">阅读时长</span><span class="post-meta-item__value">45分</span></span></div></header><div class="post-body"><!-- 页面必备样式 -->
<style>
.back-top{position: fixed;top: 500px;height: 0px;float: right;right: 50px;}
.back-top>a{font-weight:bold;width: 50px;height: 50px;text-align: center;text-decoration: none;font-size: 5px;line-height: 50px;border-radius: 50px;background-color:rgba(255,255,255,0.5);}
</style>
<div class="back-top">
    <a href="#top"> >返回顶部< </a>
</div>
<!-- toc -->
<!-- 必备样式结束 -->



        <h3 id="Mybatis是什么？"   >
          <a href="#Mybatis是什么？" class="heading-link"><i class="fas fa-link"></i></a><a href="#Mybatis是什么？" class="headerlink" title="Mybatis是什么？"></a>Mybatis是什么？</h3>
      <p>
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code，
并且改名为MyBatis 。2013年11月迁移到Github。MyBatis是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。
MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解，将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。总而言之MyBatis是一个轻量级简化数据库操作的框架。
</p>


        <h3 id="Mybatis架构"   >
          <a href="#Mybatis架构" class="heading-link"><i class="fas fa-link"></i></a><a href="#Mybatis架构" class="headerlink" title="Mybatis架构"></a>Mybatis架构</h3>
      <p><img   src="https://img-blog.csdnimg.cn/20210313165831616.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70" style="width: image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,tepx;height: t_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70px;"  alt="在这里插入图片描述"></p>

        <h3 id="Mybatis的配置文件（包括数据库连接，MapperXML配置文件位置）"   >
          <a href="#Mybatis的配置文件（包括数据库连接，MapperXML配置文件位置）" class="heading-link"><i class="fas fa-link"></i></a><a href="#Mybatis的配置文件（包括数据库连接，MapperXML配置文件位置）" class="headerlink" title="Mybatis的配置文件（包括数据库连接，MapperXML配置文件位置）"></a>Mybatis的配置文件（包括数据库连接，MapperXML配置文件位置）</h3>
      <figure class="highlight xml"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">configuration</span></span></span><br><span class="line"><span class="meta">  <span class="meta-keyword">PUBLIC</span> <span class="meta-string">&quot;-//mybatis.org//DTD Config 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">  <span class="meta-string">&quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;</span>&gt;</span></span><br><span class="line">  </span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 读取数据库连接的配置文件 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">properties</span> <span class="attr">resource</span>=<span class="string">&quot;db.properties&quot;</span>/&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!--    推荐使用package包的形式来配置别名</span></span><br><span class="line"><span class="comment">			包的形式会扫描主包及子包下的所有文件</span></span><br><span class="line"><span class="comment">			以对象类名为别名，大小写不限，推荐使用小写</span></span><br><span class="line"><span class="comment">	 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">typeAliases</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 	&lt;typeAlias type=&quot;com.sikiedu.bean.User&quot; alias=&quot;user&quot;/&gt; --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">package</span> <span class="attr">name</span>=<span class="string">&quot;com.sikiedu.bean&quot;</span>/&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">typeAliases</span>&gt;</span></span><br><span class="line">	</span><br><span class="line"> <span class="comment">&lt;!-- 在集成spring 不用environments这个property --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">environments</span> <span class="attr">default</span>=<span class="string">&quot;development&quot;</span>&gt;</span></span><br><span class="line">	  </span><br><span class="line">    <span class="tag">&lt;<span class="name">environment</span> <span class="attr">id</span>=<span class="string">&quot;development&quot;</span>&gt;</span></span><br><span class="line">		</span><br><span class="line">    <span class="comment">&lt;!-- 使用jdbc的事务 --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">transactionManager</span> <span class="attr">type</span>=<span class="string">&quot;JDBC&quot;</span>/&gt;</span></span><br><span class="line">	  </span><br><span class="line">      <span class="comment">&lt;!-- 使用连接池 连接数据库 --&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">dataSource</span> <span class="attr">type</span>=<span class="string">&quot;POOLED&quot;</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 注意下面的jdbc.driver在文件db.properties中: --&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 写法是：jdbc.driver=com.mysql.jdbc.Driver --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;driver&quot;</span> <span class="attr">value</span>=<span class="string">&quot;$&#123;jdbc.driver&#125;&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;url&quot;</span> <span class="attr">value</span>=<span class="string">&quot;$&#123;jdbc.url&#125;&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span> <span class="attr">value</span>=<span class="string">&quot;$&#123;jdbc.username&#125;&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span> <span class="attr">value</span>=<span class="string">&quot;$&#123;jdbc.password&#125;&quot;</span>/&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">dataSource</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">environment</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">environments</span>&gt;</span></span><br><span class="line">  </span><br><span class="line">  <span class="comment">&lt;!-- 配置映射器配置文件 XXX.xml 的位置 --&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">mappers</span>&gt;</span></span><br><span class="line">   	<span class="comment">&lt;!-- &lt;mapper resource=&quot;mapper/UserMapper.xml&quot;/&gt; --&gt;</span></span><br><span class="line">   	<span class="comment">&lt;!-- &lt;mapper url=&quot;file:\\\D:\Work\Siki_edu\JavaEE\Teach\SSM框架\ssm_project\ssm_mybatis\src\mapper\UserMapper.xml&quot;/&gt; --&gt;</span></span><br><span class="line">   	<span class="comment">&lt;!-- &lt;mapper class=&quot;com.sikiedu.mapper.UserMapper&quot;/&gt; --&gt;</span></span><br><span class="line">   	<span class="comment">&lt;!-- 推荐使用包的形式配置 --&gt;</span></span><br><span class="line">   	<span class="tag">&lt;<span class="name">package</span> <span class="attr">name</span>=<span class="string">&quot;com.sikiedu.mapper&quot;</span>/&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">mappers</span>&gt;</span></span><br><span class="line">  </span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></div></figure>
<p><strong>注意：</strong><br>当使用<code>&lt;package/&gt;</code>标签时 <strong>映射接口文件与映射配置文件共同应该在Mapper文件夹下</strong></p>
<p>否则使用mapper标签 且用resource指定对应的配置文件所在目录</p>

        <h3 id="Mybatis某个映射接口文件以及对应的XML文件（比如UserMapper-java-amp-UserMapper-xml"   >
          <a href="#Mybatis某个映射接口文件以及对应的XML文件（比如UserMapper-java-amp-UserMapper-xml" class="heading-link"><i class="fas fa-link"></i></a><a href="#Mybatis某个映射接口文件以及对应的XML文件（比如UserMapper-java-amp-UserMapper-xml" class="headerlink" title="Mybatis某个映射接口文件以及对应的XML文件（比如UserMapper.java &amp; UserMapper.xml)"></a>Mybatis某个映射接口文件以及对应的XML文件（比如UserMapper.java &amp; UserMapper.xml)</h3>
      <figure class="highlight xml"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">mapper</span></span></span><br><span class="line"><span class="meta">  <span class="meta-keyword">PUBLIC</span> <span class="meta-string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">  <span class="meta-string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- 注意域名namespace不要写错 相当于自己地址 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.sikiedu.mapper.UserMapper&quot;</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="tag">&lt;<span class="name">sql</span> <span class="attr">id</span>=<span class="string">&quot;myselect&quot;</span>&gt;</span></span><br><span class="line">		SELECT * </span><br><span class="line">		FROM user</span><br><span class="line">	<span class="tag">&lt;/<span class="name">sql</span>&gt;</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">&lt;!-- 根据id查询用户 --&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 注意! 标签中的id属性值,必须与对应Mapper接口文件中的方法名一致!!! --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserById&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;Integer&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;user&quot;</span>&gt;</span></span><br><span class="line">		 select * from user where u_id = #&#123;id&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 根据名字模糊查询用户 --&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- #&#123;&#125; 占位符 尽量选用#&#123;&#125;来解决问题 &#x27;1&#x27; &#x27;王&#x27;--&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- $&#123;&#125; 字符串拼接 or 1=1  王 --&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- order by $&#123;&#125; --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserByName&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;String&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;com.sikiedu.bean.User&quot;</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- SELECT * FROM USER WHERE u_username LIKE &#x27;%$&#123;value&#125;%&#x27; --&gt;</span></span><br><span class="line">		SELECT * FROM USER WHERE u_username LIKE &quot;%&quot;#&#123;name&#125;&quot;%&quot;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 添加用户 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">insert</span> <span class="attr">id</span>=<span class="string">&quot;insertUser&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.sikiedu.bean.User&quot;</span>&gt;</span></span><br><span class="line">		insert into user values( null, #&#123;u_username&#125; , #&#123;u_password&#125;, #&#123;u_sex&#125;, #&#123;u_createTime&#125;, #&#123;u_cid&#125; )</span><br><span class="line">	<span class="tag">&lt;/<span class="name">insert</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 修改用户 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">&quot;updateUser&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;com.sikiedu.bean.User&quot;</span> &gt;</span></span><br><span class="line">		update user set u_username = #&#123;u_username&#125; where u_id = #&#123;u_id&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 根据id删除用户 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">delete</span> <span class="attr">id</span>=<span class="string">&quot;deleteUserById&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;Integer&quot;</span>&gt;</span></span><br><span class="line">		delete from user Where u_id = #&#123;id&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">delete</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserByUserVoId&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;UserVo&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;user&quot;</span>&gt;</span></span><br><span class="line">		 select * from user where u_id = #&#123;user.u_id&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 	public Integer selectUserCount(); --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserCount&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;Integer&quot;</span>&gt;</span></span><br><span class="line">		Select Count(*) from user</span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line"><span class="comment">&lt;!-- public List&lt;UserVo&gt; selectAllUserVo(); //查询所有用户包装类 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">type</span>=<span class="string">&quot;UserVo&quot;</span> <span class="attr">id</span>=<span class="string">&quot;uservolist&quot;</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">id</span> <span class="attr">property</span>=<span class="string">&quot;u_id&quot;</span> <span class="attr">column</span>=<span class="string">&quot;u_id&quot;</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;u_username&quot;</span> <span class="attr">column</span>=<span class="string">&quot;u_username&quot;</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;u_sex&quot;</span> <span class="attr">column</span>=<span class="string">&quot;u_sex&quot;</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">association</span> <span class="attr">property</span>=<span class="string">&quot;country&quot;</span> <span class="attr">javaType</span>=<span class="string">&quot;Country&quot;</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">id</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span> <span class="attr">column</span>=<span class="string">&quot;c_id&quot;</span>/&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;c_countryname&quot;</span> <span class="attr">column</span>=<span class="string">&quot;c_countryname&quot;</span>/&gt;</span></span><br><span class="line">		<span class="tag">&lt;/<span class="name">association</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectAllUserVo&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;uservolist&quot;</span>&gt;</span></span><br><span class="line">		SELECT </span><br><span class="line">		u.`u_id`, </span><br><span class="line">		u.`u_username`,</span><br><span class="line">		u.`u_sex`, </span><br><span class="line">		c.`c_id`, </span><br><span class="line">		c.`c_countryname` </span><br><span class="line">		FROM USER u </span><br><span class="line">		LEFT JOIN </span><br><span class="line">		country c </span><br><span class="line">		ON u.`u_cid`=c.`c_id`</span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 	//多条件查询 通过用户对象中的条件查询用户列表</span></span><br><span class="line"><span class="comment">	public List&lt;User&gt; selectUserListByUser(User u); --&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserListByUser&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;User&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 查询用户性别 模糊查询用户名 查询用户cid 国籍ID --&gt;</span></span><br><span class="line">		SELECT * </span><br><span class="line">		FROM user</span><br><span class="line">		<span class="tag">&lt;<span class="name">where</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- where标签可以去掉开头的AND --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;u_sex != null and u_sex != &#x27;&#x27;&quot;</span>&gt;</span></span><br><span class="line">			 AND u_sex = #&#123;u_sex&#125; </span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;u_username != null and u_username != &#x27;&#x27;&quot;</span>&gt;</span></span><br><span class="line">			AND u_username like &quot;%&quot;#&#123;u_username&#125;&quot;%&quot; </span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;u_cid != null&quot;</span>&gt;</span></span><br><span class="line">			AND u_cid = #&#123;u_cid&#125;</span><br><span class="line">		<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;/<span class="name">where</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserListByUserTrim&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;User&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 查询用户性别 模糊查询用户名 查询用户cid 国籍ID --&gt;</span></span><br><span class="line">		SELECT * </span><br><span class="line">		FROM user</span><br><span class="line">		<span class="tag">&lt;<span class="name">trim</span> <span class="attr">prefix</span>=<span class="string">&quot;where&quot;</span> <span class="attr">suffixOverrides</span>=<span class="string">&quot;AND&quot;</span>&gt;</span></span><br><span class="line">			<span class="comment">&lt;!-- where标签可以去掉开头的AND --&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;u_sex != null and u_sex != &#x27;&#x27;&quot;</span>&gt;</span></span><br><span class="line">				 u_sex = #&#123;u_sex&#125; AND </span><br><span class="line">			<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;u_username != null and u_username != &#x27;&#x27;&quot;</span>&gt;</span></span><br><span class="line">				u_username like &quot;%&quot;#&#123;u_username&#125;&quot;%&quot; AND </span><br><span class="line">			<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;u_cid != null&quot;</span>&gt;</span></span><br><span class="line">				 u_cid = #&#123;u_cid&#125; AND</span><br><span class="line">			<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;/<span class="name">trim</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- public void updateSetUser(User u); --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">update</span> <span class="attr">id</span>=<span class="string">&quot;updateSetUser&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 用户名 用户密码 性别 用id来限制 --&gt;</span></span><br><span class="line">		update user </span><br><span class="line">		<span class="tag">&lt;<span class="name">set</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;u_username != null and u_username != &#x27;&#x27;&quot;</span>&gt;</span></span><br><span class="line">				u_username = #&#123;u_username&#125;,</span><br><span class="line">			<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;u_password != null and u_password != &#x27;&#x27;&quot;</span>&gt;</span></span><br><span class="line">				u_password = #&#123;u_password&#125;,</span><br><span class="line">			<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">			<span class="tag">&lt;<span class="name">if</span> <span class="attr">test</span>=<span class="string">&quot;u_sex != null and u_sex != &#x27;&#x27;&quot;</span>&gt;</span></span><br><span class="line">				u_sex = #&#123;u_sex&#125;</span><br><span class="line">			<span class="tag">&lt;/<span class="name">if</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br><span class="line">		Where u_id = #&#123;u_id&#125;</span><br><span class="line">	<span class="tag">&lt;/<span class="name">update</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 	//使用多个id获取用户列表</span></span><br><span class="line"><span class="comment">	public List&lt;User&gt; selectUserListByIds(); (1, 3, 5)--&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserListByIds&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">		SELECT * </span><br><span class="line">		FROM USER </span><br><span class="line">		WHERE u_id </span><br><span class="line">		IN </span><br><span class="line">		<span class="comment">&lt;!-- (1,2,3) --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">foreach</span> <span class="attr">collection</span>=<span class="string">&quot;array&quot;</span> <span class="attr">item</span>=<span class="string">&quot;id&quot;</span> <span class="attr">open</span>=<span class="string">&quot;(&quot;</span> <span class="attr">close</span>=<span class="string">&quot;)&quot;</span> <span class="attr">separator</span>=<span class="string">&quot;,&quot;</span>&gt;</span></span><br><span class="line">			#&#123;id&#125; </span><br><span class="line">		<span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">		<span class="comment">&lt;!-- 	//使用多个id获取用户列表</span></span><br><span class="line"><span class="comment">	public List&lt;User&gt; selectUserListByIds(); (1, 3, 5)--&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserListByList&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">		SELECT * </span><br><span class="line">		FROM USER </span><br><span class="line">		WHERE u_id </span><br><span class="line">		IN </span><br><span class="line">		<span class="comment">&lt;!-- (1,2,3) --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">foreach</span> <span class="attr">collection</span>=<span class="string">&quot;list&quot;</span> <span class="attr">item</span>=<span class="string">&quot;id&quot;</span> <span class="attr">open</span>=<span class="string">&quot;(&quot;</span> <span class="attr">close</span>=<span class="string">&quot;)&quot;</span> <span class="attr">separator</span>=<span class="string">&quot;,&quot;</span>&gt;</span></span><br><span class="line">			#&#123;id&#125; </span><br><span class="line">		<span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 	List&lt;User&gt; selectUserByVo(CountryVo vo); --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserByVo&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;CountryVo&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">include</span> <span class="attr">refid</span>=<span class="string">&quot;myselect&quot;</span>/&gt;</span></span><br><span class="line">		WHERE u_id </span><br><span class="line">		IN </span><br><span class="line">		<span class="comment">&lt;!-- (1,2,3) --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">foreach</span> <span class="attr">collection</span>=<span class="string">&quot;list&quot;</span> <span class="attr">item</span>=<span class="string">&quot;id&quot;</span> <span class="attr">open</span>=<span class="string">&quot;(&quot;</span> <span class="attr">close</span>=<span class="string">&quot;)&quot;</span> <span class="attr">separator</span>=<span class="string">&quot;,&quot;</span>&gt;</span></span><br><span class="line">			#&#123;id&#125; </span><br><span class="line">		<span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">&lt;!-- 	//使用多个id获取用户列表 by userVO</span></span><br><span class="line"><span class="comment">	public List&lt;User&gt; selectUserListByUserVo(UserVo vo); --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;selectUserListByUserVo&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;UserVo&quot;</span> <span class="attr">resultType</span>=<span class="string">&quot;User&quot;</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">include</span> <span class="attr">refid</span>=<span class="string">&quot;myselect&quot;</span>/&gt;</span></span><br><span class="line">		WHERE u_id </span><br><span class="line">		IN </span><br><span class="line">		<span class="comment">&lt;!-- (1,2,3) --&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">foreach</span> <span class="attr">collection</span>=<span class="string">&quot;idList&quot;</span> <span class="attr">item</span>=<span class="string">&quot;id&quot;</span> <span class="attr">open</span>=<span class="string">&quot;(&quot;</span> <span class="attr">close</span>=<span class="string">&quot;)&quot;</span> <span class="attr">separator</span>=<span class="string">&quot;,&quot;</span>&gt;</span></span><br><span class="line">			#&#123;id&#125; </span><br><span class="line">		<span class="tag">&lt;/<span class="name">foreach</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line">	</span><br><span class="line">	</span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></div></figure>


        <h3 id="在Mybatis中的（XXXMapper-xml）映射文件中需要注意的事项"   >
          <a href="#在Mybatis中的（XXXMapper-xml）映射文件中需要注意的事项" class="heading-link"><i class="fas fa-link"></i></a><a href="#在Mybatis中的（XXXMapper-xml）映射文件中需要注意的事项" class="headerlink" title="在Mybatis中的（XXXMapper.xml）映射文件中需要注意的事项"></a>在Mybatis中的（XXXMapper.xml）映射文件中需要注意的事项</h3>
      <ol>
<li>namespace 代表该映射文件的域名地址 不要填错</li>
<li>select标签中的id <strong>必须与对应Mapper.java文件中的方法名一致！！！</strong></li>
<li>parameterType 代表接口中方法的形参类型 要一致</li>
<li>resultType代表返回类型，以下两者均可 要一致<br>（com.sikiedu.bean.User是全称）<br>（user是Mybatis配置文件中配置好的 TypeAlias起的别名）</li>
<li>具体的SQL语句中 #{x} 的x代表UserMapper接口文件中形参名 要一致</li>
</ol>

        <h3 id="UserMapper-java文件（映射接口文件）"   >
          <a href="#UserMapper-java文件（映射接口文件）" class="heading-link"><i class="fas fa-link"></i></a><a href="#UserMapper-java文件（映射接口文件）" class="headerlink" title="UserMapper.java文件（映射接口文件）"></a>UserMapper.java文件（映射接口文件）</h3>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.sikiedu.mapper;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.sikiedu.bean.User;</span><br><span class="line"><span class="keyword">import</span> com.sikiedu.bean.UserVo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//mapper动态代理开发四大原则 + 一个注意</span></span><br><span class="line">	<span class="comment">//1、接口方法名需要与mapper.xml的要调用的sql语句的id一致</span></span><br><span class="line">	<span class="comment">//2、接口的形参类型需要与mapper.xml parameterType 一致</span></span><br><span class="line">	<span class="comment">//3、接口的返回值需要与mapper.xml resultType一致</span></span><br><span class="line">	<span class="comment">//4、mapper.xml 中namespace要与接口的全包名一致</span></span><br><span class="line">	<span class="comment">//5、注意mapper动态代理开发中，根据返回值类型来自动选择</span></span><br><span class="line">	</span><br><span class="line">	<span class="comment">//通过id查询一个用户</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> User <span class="title">selectUserById</span><span class="params">(Integer id)</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//通过用户名模糊查询 获取用户列表</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">selectUserByName</span><span class="params">(String name)</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//通过UserVo id查询一个用户</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> User <span class="title">selectUserByUserVoId</span><span class="params">(UserVo vo)</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//查询用户总条数</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> Integer <span class="title">selectUserCount</span><span class="params">()</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//查询所有用户包装类</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> List&lt;UserVo&gt; <span class="title">selectAllUserVo</span><span class="params">()</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//多条件查询 通过用户对象中的条件查询用户列表</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">selectUserListByUser</span><span class="params">(User u)</span></span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//多条件查询 通过用户对象中的条件查询用户列表Trim</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">selectUserListByUserTrim</span><span class="params">(User u)</span></span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//更新用户表</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateSetUser</span><span class="params">(User u)</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//使用多个id获取用户列表 by array</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">selectUserListByIds</span><span class="params">(Integer[] ids)</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//使用多个id获取用户列表 by list</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">selectUserListByList</span><span class="params">(List&lt;Integer&gt; idList)</span></span>;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//使用多个id获取用户列表 by userVO</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">selectUserListByUserVo</span><span class="params">(UserVo vo)</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></div></figure>


        <h3 id="与数据库中相对应的实体类文件（XXX-java"   >
          <a href="#与数据库中相对应的实体类文件（XXX-java" class="heading-link"><i class="fas fa-link"></i></a><a href="#与数据库中相对应的实体类文件（XXX-java" class="headerlink" title="与数据库中相对应的实体类文件（XXX.java)"></a>与数据库中相对应的实体类文件（XXX.java)</h3>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.sikiedu.bean;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * CREATE TABLE `user` (</span></span><br><span class="line"><span class="comment">	  `u_id` INT(11) NOT NULL AUTO_INCREMENT COMMENT &#x27;用户id&#x27;,</span></span><br><span class="line"><span class="comment">	  `u_username` VARCHAR(64) NOT NULL COMMENT &#x27;用户名&#x27;,</span></span><br><span class="line"><span class="comment">	  `u_password` VARCHAR(64) NOT NULL COMMENT &#x27;用户密码&#x27;,</span></span><br><span class="line"><span class="comment">	  `u_sex` VARCHAR(16) DEFAULT NULL COMMENT &#x27;用户性别&#x27;,</span></span><br><span class="line"><span class="comment">	  `u_createTime` DATETIME DEFAULT NULL COMMENT &#x27;用户创建时间&#x27;,</span></span><br><span class="line"><span class="comment">	  `u_cid` INT(11) NOT NULL COMMENT &#x27;用户国家id&#x27;,</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	</span><br><span class="line">	<span class="keyword">private</span> Integer u_id;</span><br><span class="line">	<span class="keyword">private</span> String u_username;</span><br><span class="line">	<span class="keyword">private</span> String u_password;</span><br><span class="line">	<span class="keyword">private</span> String u_sex;</span><br><span class="line">	<span class="keyword">private</span> Date u_createTime;</span><br><span class="line">	<span class="keyword">private</span> Integer u_cid;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> Integer <span class="title">getU_id</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> u_id;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setU_id</span><span class="params">(Integer u_id)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.u_id = u_id;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getU_username</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> u_username;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setU_username</span><span class="params">(String u_username)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.u_username = u_username;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getU_password</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> u_password;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setU_password</span><span class="params">(String u_password)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.u_password = u_password;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getU_sex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> u_sex;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setU_sex</span><span class="params">(String u_sex)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.u_sex = u_sex;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> Date <span class="title">getU_createTime</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> u_createTime;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setU_createTime</span><span class="params">(Date u_createTime)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.u_createTime = u_createTime;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> Integer <span class="title">getU_cid</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> u_cid;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setU_cid</span><span class="params">(Integer u_cid)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.u_cid = u_cid;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="string">&quot;User [u_id=&quot;</span> + u_id + <span class="string">&quot;, u_username=&quot;</span> + u_username + <span class="string">&quot;, u_password=&quot;</span> + u_password + <span class="string">&quot;, u_sex=&quot;</span> + u_sex</span><br><span class="line">				+ <span class="string">&quot;, u_createTime=&quot;</span> + u_createTime + <span class="string">&quot;, u_cid=&quot;</span> + u_cid + <span class="string">&quot;]&quot;</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></div></figure>

<ol>
<li><strong>推荐类名的私有变量的名字完全与数据库中字段名相同</strong></li>
<li>给相应<strong>Set、Get方法</strong>即可</li>
<li><strong>toString方法</strong></li>
</ol>

        <h3 id="函数如何调用完整的Mybatis过程-增删改查"   >
          <a href="#函数如何调用完整的Mybatis过程-增删改查" class="heading-link"><i class="fas fa-link"></i></a><a href="#函数如何调用完整的Mybatis过程-增删改查" class="headerlink" title="函数如何调用完整的Mybatis过程(增删改查)"></a>函数如何调用完整的Mybatis过程(增删改查)</h3>
      
        <h4 id="一、selectOne-函数（查询）"   >
          <a href="#一、selectOne-函数（查询）" class="heading-link"><i class="fas fa-link"></i></a><a href="#一、selectOne-函数（查询）" class="headerlink" title="一、selectOne 函数（查询）"></a>一、selectOne 函数（查询）</h4>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">	<span class="comment">//入门程序 通过ID 查询用户</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Test1</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">		String resource = <span class="string">&quot;sqlMapConfig.xml&quot;</span>;</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//读取配置文件</span></span><br><span class="line">		InputStream in = Resources.getResourceAsStream(resource);</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//需要sqlSessionFactoryBulider</span></span><br><span class="line">		SqlSessionFactoryBuilder ssfb = <span class="keyword">new</span> SqlSessionFactoryBuilder();</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//创建sqlSessionfactory</span></span><br><span class="line">		SqlSessionFactory ssf = ssfb.build(in);</span><br><span class="line">		 </span><br><span class="line">		<span class="comment">//生产一个sqlSession</span></span><br><span class="line">		SqlSession session = ssf.openSession();</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//操作数据库</span></span><br><span class="line">		<span class="comment">//参数1：要操作的接口方法   参数2 sql语句的参数</span></span><br><span class="line">		User user = session.selectOne(<span class="string">&quot;UserMapper.selectUserById&quot;</span>, <span class="number">1</span>);</span><br><span class="line">		System.out.println(user);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></div></figure>


        <h4 id="二、session的getMapper方法-找到Dao层接口类（查询）"   >
          <a href="#二、session的getMapper方法-找到Dao层接口类（查询）" class="heading-link"><i class="fas fa-link"></i></a><a href="#二、session的getMapper方法-找到Dao层接口类（查询）" class="headerlink" title="二、session的getMapper方法 找到Dao层接口类（查询）"></a>二、session的getMapper方法 找到Dao层接口类（查询）</h4>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">String resource = <span class="string">&quot;sqlMapConfig.xml&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//读取配置文件</span></span><br><span class="line">InputStream in = Resources.getResourceAsStream(resource);</span><br><span class="line"><span class="comment">//需要sqlSessionFactoryBulider</span></span><br><span class="line">SqlSessionFactoryBuilder ssfb = <span class="keyword">new</span> SqlSessionFactoryBuilder();</span><br><span class="line"><span class="comment">//创建sqlSessionfactory</span></span><br><span class="line">SqlSessionFactory ssf = ssfb.build(in);</span><br><span class="line"></span><br><span class="line"><span class="comment">//将IUser加入工厂中 以getMapper找到</span></span><br><span class="line">sqlSessionFactory.getConfiguration().addMapper(IUser.class);</span><br><span class="line">SqlSession session = sqlSessionFactory.openSession();</span><br><span class="line"></span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">	<span class="comment">//通过getMapper方法 找到IUser接口类</span></span><br><span class="line">          IUser iuser = session.getMapper(IUser.class);</span><br><span class="line">	<span class="comment">//调用相应方法（增删改查）</span></span><br><span class="line">          User user = iuser.getUserByID(<span class="number">1</span>);</span><br><span class="line">          System.out.println(<span class="string">&quot;名字：&quot;</span>+user.getName());</span><br><span class="line">      &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">          session.close();</span><br><span class="line">      &#125;</span><br></pre></td></tr></table></div></figure>

<p><strong>Mybatis的调用过程中：</strong></p>
<ol>
<li>首先需要输入流 读取配置文件sqlMapConfig.xml</li>
<li>需要一个工厂建造者Builder 来利用这个输入流建造</li>
<li>建造返回一个工厂 用这个工厂打开一次会话</li>
<li>在会话中Select…等等</li>
<li>对于更改操作（插入、更新、删除）记得<strong>session.commit()</strong></li>
<li>session的对应方法 <strong>第一个参数是通过XXXMapper.对应方法 第二个是传入的实参</strong></li>
</ol>

        <h4 id="三、session的getMapper方法-找到Dao层接口类（插入）"   >
          <a href="#三、session的getMapper方法-找到Dao层接口类（插入）" class="heading-link"><i class="fas fa-link"></i></a><a href="#三、session的getMapper方法-找到Dao层接口类（插入）" class="headerlink" title="三、session的getMapper方法 找到Dao层接口类（插入）"></a>三、session的getMapper方法 找到Dao层接口类（插入）</h4>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">....忽略配置文件加载、SQLSession建造者、工厂....</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">	<span class="comment">//通过getMapper方法 找到IUser接口类</span></span><br><span class="line">    IUser iuser = session.getMapper(IUser.class);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//假设该接口类有 void方法insertUser(User user)</span></span><br><span class="line">    User user = <span class="keyword">new</span> User();</span><br><span class="line">	user.setXXX(<span class="string">&quot;xxx&quot;</span>);</span><br><span class="line">	...set方法</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//插入数据 记得提交会话（包括删除操作、更新操作）</span></span><br><span class="line">	iuser.insertUser(user);</span><br><span class="line">	session.commit();</span><br><span class="line">	</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    session.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure>


        <h4 id="四、session的getMapper方法-找到Dao层接口类（更新）"   >
          <a href="#四、session的getMapper方法-找到Dao层接口类（更新）" class="heading-link"><i class="fas fa-link"></i></a><a href="#四、session的getMapper方法-找到Dao层接口类（更新）" class="headerlink" title="四、session的getMapper方法 找到Dao层接口类（更新）"></a>四、session的getMapper方法 找到Dao层接口类（更新）</h4>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">....忽略配置文件加载、SQLSession建造者、工厂....</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">	<span class="comment">//通过getMapper方法 找到IUser接口类</span></span><br><span class="line">    IUser iuser = session.getMapper(IUser.class);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//首先通过相应属性找到user</span></span><br><span class="line">	User user = iuser.getUserById(<span class="number">1</span>);</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//假设该接口类有 void方法updateUser(User user)</span></span><br><span class="line">	<span class="comment">//将user的name更改为Vincent</span></span><br><span class="line">	user.setName(<span class="string">&quot;Vincent&quot;</span>);</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//更新数据 记得提交会话</span></span><br><span class="line">	iuser.updateUser(user);</span><br><span class="line">	session.commit();</span><br><span class="line">	</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    session.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure>


        <h4 id="五、session的getMapper方法-找到Dao层接口类（删除）"   >
          <a href="#五、session的getMapper方法-找到Dao层接口类（删除）" class="heading-link"><i class="fas fa-link"></i></a><a href="#五、session的getMapper方法-找到Dao层接口类（删除）" class="headerlink" title="五、session的getMapper方法 找到Dao层接口类（删除）"></a>五、session的getMapper方法 找到Dao层接口类（删除）</h4>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">....忽略配置文件加载、SQLSession建造者、工厂....</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">	<span class="comment">//通过getMapper方法 找到IUser接口类</span></span><br><span class="line">    IUser iuser = session.getMapper(IUser.class);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//首先通过相应属性找到user</span></span><br><span class="line">	User user = iuser.getUserById(<span class="number">1</span>);</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//假设该接口类有方法 deleteUser(User user)</span></span><br><span class="line">	<span class="comment">//记得提交会话</span></span><br><span class="line">	</span><br><span class="line">	iuser.deleteUser(user);</span><br><span class="line">	session.commit();</span><br><span class="line">	</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">    session.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure>



        <h3 id="ResultMap：解决数据库字段与Java实体类的属性不一致问题"   >
          <a href="#ResultMap：解决数据库字段与Java实体类的属性不一致问题" class="heading-link"><i class="fas fa-link"></i></a><a href="#ResultMap：解决数据库字段与Java实体类的属性不一致问题" class="headerlink" title="ResultMap：解决数据库字段与Java实体类的属性不一致问题"></a>ResultMap：解决数据库字段与Java实体类的属性不一致问题</h3>
      
        <h4 id="1-Result实现JavaBean对象与数据库column名字不一样的映射"   >
          <a href="#1-Result实现JavaBean对象与数据库column名字不一样的映射" class="heading-link"><i class="fas fa-link"></i></a><a href="#1-Result实现JavaBean对象与数据库column名字不一样的映射" class="headerlink" title="1.Result实现JavaBean对象与数据库column名字不一样的映射"></a>1.Result实现JavaBean对象与数据库column名字不一样的映射</h4>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- type表示具体的Java类 id随便取-唯一标识即可 --&gt;</span><br><span class="line">&lt;resultMap type=<span class="string">&quot;CountryVo&quot;</span> id=<span class="string">&quot;countryVo&quot;</span>&gt;</span><br><span class="line">		</span><br><span class="line">		&lt;!-- id标签是主键 property是Java类中的属性 column是对应Java类在数据库表中的字段 --&gt;</span><br><span class="line">		&lt;id property=<span class="string">&quot;id&quot;</span> column=<span class="string">&quot;c_id&quot;</span>/&gt;</span><br><span class="line"></span><br><span class="line">		&lt;!-- result可以是若干个其他 非主键属性的对应 --&gt;</span><br><span class="line">		&lt;result property=<span class="string">&quot;c_countryname&quot;</span> column=<span class="string">&quot;c_countryname&quot;</span>/&gt;</span><br><span class="line">		&lt;result property=<span class="string">&quot;c_capital&quot;</span> column=<span class="string">&quot;c_capital&quot;</span>/&gt;</span><br><span class="line">&lt;/resultMap&gt;</span><br></pre></td></tr></table></div></figure>


        <h4 id="2-Result实现一对多映射-Collection"   >
          <a href="#2-Result实现一对多映射-Collection" class="heading-link"><i class="fas fa-link"></i></a><a href="#2-Result实现一对多映射-Collection" class="headerlink" title="2.Result实现一对多映射 Collection"></a>2.Result实现一对多映射 Collection</h4>
      <p>比如一个用户User 有多个帖子Post<br>现在查询对应的User 查看这个User下的所有帖子（因此帖子是集合<code>java private List&lt;Post&gt; posts;</code>)</p>
<p>1.User类</p>
<figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">//要实现序列化Serializable</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> <span class="keyword">implements</span> <span class="title">Serializable</span></span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> id;</span><br><span class="line">	<span class="keyword">private</span> String username;</span><br><span class="line">	<span class="keyword">private</span> String mobile;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">//一个User 对应多个Post 因此用集合</span></span><br><span class="line">	<span class="keyword">private</span> List&lt;Post&gt; posts;</span><br><span class="line">	</span><br><span class="line">	...忽略set get方法以及toString方法</span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure>

<p>2.Post类</p>
<figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Post</span> <span class="keyword">implements</span> <span class="title">Serializable</span></span>&#123;</span><br><span class="line">	<span class="comment">//查询的时候 post.id 应该等于 user.id</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> id;</span><br><span class="line">	<span class="keyword">private</span> User user;</span><br><span class="line">	<span class="keyword">private</span> String title;</span><br><span class="line">	<span class="keyword">private</span> String content;</span><br><span class="line">	...忽略set get方法以及toString方法</span><br><span class="line">&#125;</span><br></pre></td></tr></table></div></figure>

<p>3.ResultMap配置一个用户多个帖子的映射</p>
<figure class="highlight xml"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 在一个User中配置 多个collection --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">type</span>=<span class="string">&quot;User&quot;</span> <span class="attr">id</span>=<span class="string">&quot;resultUserMap&quot;</span>&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span> <span class="attr">column</span>=<span class="string">&quot;user_id&quot;</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;username&quot;</span> <span class="attr">column</span>=<span class="string">&quot;username&quot;</span> /&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;mobile&quot;</span> <span class="attr">column</span>=<span class="string">&quot;mobile&quot;</span> /&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- collection代表多  --&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- posts代表User类中 集合的名字！column代表post表中的那个字段 与user联系 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">collection</span> <span class="attr">property</span>=<span class="string">&quot;posts&quot;</span> <span class="attr">ofType</span>=<span class="string">&quot;com.yiibai.pojo.Post&quot;</span> <span class="attr">column</span>=<span class="string">&quot;userid&quot;</span>&gt;</span></span><br><span class="line">		<span class="tag">&lt;<span class="name">id</span> <span class="attr">property</span>=<span class="string">&quot;id&quot;</span> <span class="attr">column</span>=<span class="string">&quot;post_id&quot;</span> <span class="attr">javaType</span>=<span class="string">&quot;int&quot;</span> <span class="attr">jdbcType</span>=<span class="string">&quot;INTEGER&quot;</span>/&gt;</span>    </span><br><span class="line">           <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;title&quot;</span> <span class="attr">column</span>=<span class="string">&quot;title&quot;</span> <span class="attr">javaType</span>=<span class="string">&quot;string&quot;</span> <span class="attr">jdbcType</span>=<span class="string">&quot;VARCHAR&quot;</span>/&gt;</span></span><br><span class="line">           <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">&quot;content&quot;</span> <span class="attr">column</span>=<span class="string">&quot;content&quot;</span> <span class="attr">javaType</span>=<span class="string">&quot;string&quot;</span> <span class="attr">jdbcType</span>=<span class="string">&quot;VARCHAR&quot;</span>/&gt;</span> </span><br><span class="line">	<span class="tag">&lt;/<span class="name">collection</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></span><br></pre></td></tr></table></div></figure>

<p>4.SQL语句</p>
<figure class="highlight xml"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 指定结果映射为resultUserMap 需要跟相应resultMap标签的id相同 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">&quot;getUser&quot;</span> <span class="attr">resultMap</span>=<span class="string">&quot;resultUserMap&quot;</span> <span class="attr">parameterType</span>=<span class="string">&quot;int&quot;</span>&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 建立映射就是为了 能够映射SELECT后面的内容:u.*, p.* --&gt;</span></span><br><span class="line">		<span class="comment">&lt;!-- 没有建立映射的property返回的值不会显示在后台里 --&gt;</span></span><br><span class="line">		SELECT u.*,p.*</span><br><span class="line">		FROM user u, post p</span><br><span class="line">		WHERE u.id=p.userid AND id=#&#123;user_id&#125; </span><br><span class="line"> <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br></pre></td></tr></table></div></figure>

<p><strong>2021.4.6更新：</strong></p>
<ol>
<li>注意都实现<strong>Serializable</strong>接口</li>
<li>注意，如果两张表中的字段重复了，记得在Select字段中起别名</li>
<li>collection中的id标签 不会指两者映射的id <strong>而只是指这个表的主键！</strong></li>
<li>真正映射一对多的 是collection中的<strong>column属性</strong></li>
</ol>
<p>起别名代码：</p>
<figure class="highlight sql"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="operator">&lt;</span><span class="keyword">select</span><span class="operator">&gt;</span></span><br><span class="line">	<span class="keyword">select</span> u.id <span class="keyword">as</span> u_id, u.<span class="operator">*</span>, p.id <span class="keyword">as</span> p_id,p.<span class="operator">*</span></span><br><span class="line">	<span class="keyword">from</span> <span class="keyword">user</span> u, post p</span><br><span class="line">	<span class="keyword">where</span> u.u_id <span class="operator">=</span> p.p_id <span class="keyword">AND</span> u.u_id <span class="operator">=</span> #&#123;id&#125;</span><br><span class="line"><span class="operator">&lt;</span><span class="operator">/</span><span class="keyword">select</span><span class="operator">&gt;</span>	</span><br><span class="line"></span><br></pre></td></tr></table></div></figure>


        <h3 id="Mybatis-plust新特性：代码生成器"   >
          <a href="#Mybatis-plust新特性：代码生成器" class="heading-link"><i class="fas fa-link"></i></a><a href="#Mybatis-plust新特性：代码生成器" class="headerlink" title="Mybatis_plust新特性：代码生成器"></a>Mybatis_plust新特性：代码生成器</h3>
      <p><strong>注意，这里的代码指的是：</strong></p>
<p><strong>1. DAO层的XXXMapper.java接口<br>2. DAO层的XXXMapper.xml文件<br>3. Model层的XXXExample.java类 方便提前处理数据</strong></p>

        <h4 id="1-需要的插件（IDEA右侧-MAVEN里面的插件双击启动）"   >
          <a href="#1-需要的插件（IDEA右侧-MAVEN里面的插件双击启动）" class="heading-link"><i class="fas fa-link"></i></a><a href="#1-需要的插件（IDEA右侧-MAVEN里面的插件双击启动）" class="headerlink" title="1.需要的插件（IDEA右侧 MAVEN里面的插件双击启动）"></a>1.需要的插件（IDEA右侧 MAVEN里面的插件双击启动）</h4>
      <figure class="highlight java"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;plugin&gt;</span><br><span class="line">	&lt;groupId&gt;org.mybatis.generator&lt;/groupId&gt;</span><br><span class="line">	&lt;artifactId&gt;mybatis-generator-maven-plugin&lt;/artifactId&gt;</span><br><span class="line">	&lt;configuration&gt;</span><br><span class="line">		&lt;configurationFile&gt;$&#123;basedir&#125;/src/main/resources/mybatis-generator/generatorConfig.xml</span><br><span class="line">		&lt;/configurationFile&gt;</span><br><span class="line">		&lt;overwrite&gt;<span class="keyword">true</span>&lt;/overwrite&gt;</span><br><span class="line">		&lt;verbose&gt;<span class="keyword">true</span>&lt;/verbose&gt;</span><br><span class="line">	&lt;/configuration&gt;</span><br><span class="line">&lt;/plugin&gt;</span><br></pre></td></tr></table></div></figure>

<p>项目结构图：</p>
<p><img   src="https://img-blog.csdnimg.cn/20210410185916946.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70" style="width: image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,tepx;height: t_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70px;"  alt="在这里插入图片描述"></p>

        <h4 id="2-配置文件-generatorConfig-xml"   >
          <a href="#2-配置文件-generatorConfig-xml" class="heading-link"><i class="fas fa-link"></i></a><a href="#2-配置文件-generatorConfig-xml" class="headerlink" title="2.配置文件 generatorConfig.xml"></a>2.配置文件 generatorConfig.xml</h4>
      <p><strong>这一步很关键，要避免多次生成重复的BaseResultMap</strong></p>
<p><strong>注意对应Mapper.java/ Mapper.xml在项目结构图中的位置</strong></p>
<figure class="highlight xml"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">generatorConfiguration</span></span></span><br><span class="line"><span class="meta">        <span class="meta-keyword">PUBLIC</span> <span class="meta-string">&quot;-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN&quot;</span></span></span><br><span class="line"><span class="meta">        <span class="meta-string">&quot;http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">generatorConfiguration</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--    连接数据库jar包的路径--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">classPathEntry</span> <span class="attr">location</span>=<span class="string">&quot;C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\8.0.23/mysql-connector-java-8.0.23.jar&quot;</span>/&gt;</span></span><br><span class="line">    </span><br><span class="line">	<span class="tag">&lt;<span class="name">context</span> <span class="attr">id</span>=<span class="string">&quot;DB2Tables&quot;</span>  <span class="attr">targetRuntime</span>=<span class="string">&quot;MyBatis3&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">commentGenerator</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;suppressDate&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line">            <span class="comment">&lt;!-- 是否去除自动生成的注释 true：是 ： false:否 --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;suppressAllComments&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">commentGenerator</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!--数据库连接参数 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">jdbcConnection</span></span></span><br><span class="line"><span class="tag">                <span class="attr">driverClass</span>=<span class="string">&quot;com.mysql.jdbc.Driver&quot;</span></span></span><br><span class="line"><span class="tag">                <span class="attr">connectionURL</span>=<span class="string">&quot;jdbc:mysql://localhost:3306/vue_demo?serverTimezone=UTC<span class="symbol">&amp;amp;</span>useSSL=true&quot;</span></span></span><br><span class="line"><span class="tag">                <span class="attr">userId</span>=<span class="string">&quot;root&quot;</span></span></span><br><span class="line"><span class="tag">                <span class="attr">password</span>=<span class="string">&quot;123456&quot;</span>&gt;</span></span><br><span class="line">	<span class="comment">&lt;!-- 避免生成重复的BaseResultMap --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;nullCatalogMeansCurrent&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">jdbcConnection</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">javaTypeResolver</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;forceBigDecimals&quot;</span> <span class="attr">value</span>=<span class="string">&quot;false&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">javaTypeResolver</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- 实体类的包名和存放路径 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">javaModelGenerator</span> <span class="attr">targetPackage</span>=<span class="string">&quot;com.example.demo.entity&quot;</span> <span class="attr">targetProject</span>=<span class="string">&quot;src/main/java&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;enableSubPackages&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;trimStrings&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">javaModelGenerator</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- 生成映射文件*.xml的位置--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">sqlMapGenerator</span> <span class="attr">targetPackage</span>=<span class="string">&quot;mybatis&quot;</span> <span class="attr">targetProject</span>=<span class="string">&quot;src/main/resources&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;enableSubPackages&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">sqlMapGenerator</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- 生成DAO的包名和位置 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">javaClientGenerator</span> <span class="attr">type</span>=<span class="string">&quot;XMLMAPPER&quot;</span> <span class="attr">targetPackage</span>=<span class="string">&quot;com.example.demo.repository&quot;</span> <span class="attr">targetProject</span>=<span class="string">&quot;src/main/java&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;enableSubPackages&quot;</span> <span class="attr">value</span>=<span class="string">&quot;true&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">javaClientGenerator</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">&lt;!-- tableName：数据库中的表名或视图名；domainObjectName：生成的实体类的类名--&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--&lt;table tableName=&quot;book&quot; domainObjectName=&quot;Book&quot;/&gt;--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">table</span> <span class="attr">schema</span>=<span class="string">&quot;catalog&quot;</span> <span class="attr">tableName</span>=<span class="string">&quot;user&quot;</span> <span class="attr">domainObjectName</span>=<span class="string">&quot;User&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;/<span class="name">context</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">generatorConfiguration</span>&gt;</span></span><br></pre></td></tr></table></div></figure>


        <h3 id="Mybatis中出现的问题："   >
          <a href="#Mybatis中出现的问题：" class="heading-link"><i class="fas fa-link"></i></a><a href="#Mybatis中出现的问题：" class="headerlink" title="Mybatis中出现的问题："></a>Mybatis中出现的问题：</h3>
      
        <h4 id="1-UserMapper-xml到底应该放在那里？"   >
          <a href="#1-UserMapper-xml到底应该放在那里？" class="heading-link"><i class="fas fa-link"></i></a><a href="#1-UserMapper-xml到底应该放在那里？" class="headerlink" title="1.UserMapper.xml到底应该放在那里？"></a>1.UserMapper.xml到底应该放在那里？</h4>
      <p><strong>注意，在集成SpringBoot时</strong></p>
<ol>
<li><p>首先确保 <strong>UserMapper.java要有@Mapper注解</strong></p>
</li>
<li><p>其次，要注意<strong>在SpringBoot配置文件application.yml中：</strong></p>
</li>
</ol>
<figure class="highlight yml"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">mybatis:</span></span><br><span class="line">	<span class="attr">mapper-locations:</span> <span class="string">classpath:mybatis/*.xml</span></span><br></pre></td></tr></table></div></figure>

<p>并且项目结构图如下：<br><img   src="https://img-blog.csdnimg.cn/20210406191232940.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70" style="width: image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,tepx;height: t_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzQzNDQ1MDY3,size_16,color_FFFFFF,t_70px;"  alt="在这里插入图片描述"></p>
<ol start="3">
<li>UserMapper.xml中的namespace是UserMapper.java的具体位置</li>
</ol>
<p><strong>或者代码generator生成的配置文件中配置</strong></p>
<figure class="highlight xml"><div class="table-container"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">mapper</span> <span class="attr">namespace</span>=<span class="string">&quot;com.example.demo.repository.UserMapper&quot;</span>&gt;</span> </span><br><span class="line"><span class="tag">&lt;/<span class="name">mapper</span>&gt;</span></span><br></pre></td></tr></table></div></figure>


        <h4 id="配置实体类应该注意的问题"   >
          <a href="#配置实体类应该注意的问题" class="heading-link"><i class="fas fa-link"></i></a><a href="#配置实体类应该注意的问题" class="headerlink" title="配置实体类应该注意的问题"></a>配置实体类应该注意的问题</h4>
      <p><strong>1. 尽量让实体类中的各个private属性名字与数据库的字段名字相同</strong></p>
<p><strong>2. 用封装类！不要用int，而是应该用<code>Integer</code></strong></p>
<p><strong>3. 如果实体类中的属性名与数据库中的字段名相同，这样mapper中参数为实体类时，才能返回</strong></p>
</div><footer class="post-footer"><div class="post-ending ending"><div class="ending__text">------ 本文结束，感谢您的阅读 ------</div></div><div class="post-copyright copyright"><div class="copyright-author"><span class="copyright-author__name">本文作者: </span><span class="copyright-author__value"><a href="https://bruce-jj.gitee.io/blog">何水浪</a></span></div><div class="copyright-link"><span class="copyright-link__name">本文链接: </span><span class="copyright-link__value"><a href="https://bruce-jj.gitee.io/blog/2021/03/11/Mybatis/">https://bruce-jj.gitee.io/blog/2021/03/11/Mybatis/</a></span></div><div class="copyright-notice"><span class="copyright-notice__name">版权声明: </span><span class="copyright-notice__value">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" rel="external nofollow" target="_blank">BY-NC-SA</a> 许可协议。转载请注明出处！</span></div></div><div class="post-tags"><span class="post-tags-item"><span class="post-tags-item__icon"><i class="fas fa-tag"></i></span><a class="post-tags-item__link" href="https://bruce-jj.gitee.io/blog/tags/SSM%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">SSM学习笔记</a></span></div><nav class="post-paginator paginator"><div class="paginator-prev"><a class="paginator-prev__link" href="/blog/2021/03/11/%E7%9B%AE%E5%BD%95%E6%B5%8B%E8%AF%95/"><span class="paginator-prev__icon"><i class="fas fa-angle-left"></i></span><span class="paginator-prev__text">目录测试</span></a></div><div class="paginator-next"><a class="paginator-next__link" href="/blog/2021/03/11/%E4%B8%8D%E4%BC%9A%E5%90%A7%E8%80%83%E7%A0%94%E8%8B%B1%E8%AF%AD/"><span class="paginator-prev__text">不会吧？都2021年了，还有人觉得考研英语简单！？</span><span class="paginator-next__icon"><i class="fas fa-angle-right"></i></span></a></div></nav></footer></div></div><div class="comments" id="comments"><div id="valine-container"></div></div></div><div class="sidebar-wrap" id="sidebar-wrap"><aside class="sidebar" id="sidebar"><div class="sidebar-nav"><span class="sidebar-nav-toc current">文章目录</span><span class="sidebar-nav-ov">站点概览</span></div><section class="sidebar-toc"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Mybatis%E6%98%AF%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="toc-number">1.</span> <span class="toc-text">
          Mybatis是什么？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Mybatis%E6%9E%B6%E6%9E%84"><span class="toc-number">2.</span> <span class="toc-text">
          Mybatis架构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Mybatis%E7%9A%84%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%EF%BC%88%E5%8C%85%E6%8B%AC%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%EF%BC%8CMapperXML%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E4%BD%8D%E7%BD%AE%EF%BC%89"><span class="toc-number">3.</span> <span class="toc-text">
          Mybatis的配置文件（包括数据库连接，MapperXML配置文件位置）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Mybatis%E6%9F%90%E4%B8%AA%E6%98%A0%E5%B0%84%E6%8E%A5%E5%8F%A3%E6%96%87%E4%BB%B6%E4%BB%A5%E5%8F%8A%E5%AF%B9%E5%BA%94%E7%9A%84XML%E6%96%87%E4%BB%B6%EF%BC%88%E6%AF%94%E5%A6%82UserMapper-java-amp-UserMapper-xml"><span class="toc-number">4.</span> <span class="toc-text">
          Mybatis某个映射接口文件以及对应的XML文件（比如UserMapper.java &amp; UserMapper.xml)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9C%A8Mybatis%E4%B8%AD%E7%9A%84%EF%BC%88XXXMapper-xml%EF%BC%89%E6%98%A0%E5%B0%84%E6%96%87%E4%BB%B6%E4%B8%AD%E9%9C%80%E8%A6%81%E6%B3%A8%E6%84%8F%E7%9A%84%E4%BA%8B%E9%A1%B9"><span class="toc-number">5.</span> <span class="toc-text">
          在Mybatis中的（XXXMapper.xml）映射文件中需要注意的事项</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#UserMapper-java%E6%96%87%E4%BB%B6%EF%BC%88%E6%98%A0%E5%B0%84%E6%8E%A5%E5%8F%A3%E6%96%87%E4%BB%B6%EF%BC%89"><span class="toc-number">6.</span> <span class="toc-text">
          UserMapper.java文件（映射接口文件）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%8E%E6%95%B0%E6%8D%AE%E5%BA%93%E4%B8%AD%E7%9B%B8%E5%AF%B9%E5%BA%94%E7%9A%84%E5%AE%9E%E4%BD%93%E7%B1%BB%E6%96%87%E4%BB%B6%EF%BC%88XXX-java"><span class="toc-number">7.</span> <span class="toc-text">
          与数据库中相对应的实体类文件（XXX.java)</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%E5%A6%82%E4%BD%95%E8%B0%83%E7%94%A8%E5%AE%8C%E6%95%B4%E7%9A%84Mybatis%E8%BF%87%E7%A8%8B-%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5"><span class="toc-number">8.</span> <span class="toc-text">
          函数如何调用完整的Mybatis过程(增删改查)</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%80%E3%80%81selectOne-%E5%87%BD%E6%95%B0%EF%BC%88%E6%9F%A5%E8%AF%A2%EF%BC%89"><span class="toc-number">8.1.</span> <span class="toc-text">
          一、selectOne 函数（查询）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%8C%E3%80%81session%E7%9A%84getMapper%E6%96%B9%E6%B3%95-%E6%89%BE%E5%88%B0Dao%E5%B1%82%E6%8E%A5%E5%8F%A3%E7%B1%BB%EF%BC%88%E6%9F%A5%E8%AF%A2%EF%BC%89"><span class="toc-number">8.2.</span> <span class="toc-text">
          二、session的getMapper方法 找到Dao层接口类（查询）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%89%E3%80%81session%E7%9A%84getMapper%E6%96%B9%E6%B3%95-%E6%89%BE%E5%88%B0Dao%E5%B1%82%E6%8E%A5%E5%8F%A3%E7%B1%BB%EF%BC%88%E6%8F%92%E5%85%A5%EF%BC%89"><span class="toc-number">8.3.</span> <span class="toc-text">
          三、session的getMapper方法 找到Dao层接口类（插入）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9B%9B%E3%80%81session%E7%9A%84getMapper%E6%96%B9%E6%B3%95-%E6%89%BE%E5%88%B0Dao%E5%B1%82%E6%8E%A5%E5%8F%A3%E7%B1%BB%EF%BC%88%E6%9B%B4%E6%96%B0%EF%BC%89"><span class="toc-number">8.4.</span> <span class="toc-text">
          四、session的getMapper方法 找到Dao层接口类（更新）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%94%E3%80%81session%E7%9A%84getMapper%E6%96%B9%E6%B3%95-%E6%89%BE%E5%88%B0Dao%E5%B1%82%E6%8E%A5%E5%8F%A3%E7%B1%BB%EF%BC%88%E5%88%A0%E9%99%A4%EF%BC%89"><span class="toc-number">8.5.</span> <span class="toc-text">
          五、session的getMapper方法 找到Dao层接口类（删除）</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ResultMap%EF%BC%9A%E8%A7%A3%E5%86%B3%E6%95%B0%E6%8D%AE%E5%BA%93%E5%AD%97%E6%AE%B5%E4%B8%8EJava%E5%AE%9E%E4%BD%93%E7%B1%BB%E7%9A%84%E5%B1%9E%E6%80%A7%E4%B8%8D%E4%B8%80%E8%87%B4%E9%97%AE%E9%A2%98"><span class="toc-number">9.</span> <span class="toc-text">
          ResultMap：解决数据库字段与Java实体类的属性不一致问题</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-Result%E5%AE%9E%E7%8E%B0JavaBean%E5%AF%B9%E8%B1%A1%E4%B8%8E%E6%95%B0%E6%8D%AE%E5%BA%93column%E5%90%8D%E5%AD%97%E4%B8%8D%E4%B8%80%E6%A0%B7%E7%9A%84%E6%98%A0%E5%B0%84"><span class="toc-number">9.1.</span> <span class="toc-text">
          1.Result实现JavaBean对象与数据库column名字不一样的映射</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-Result%E5%AE%9E%E7%8E%B0%E4%B8%80%E5%AF%B9%E5%A4%9A%E6%98%A0%E5%B0%84-Collection"><span class="toc-number">9.2.</span> <span class="toc-text">
          2.Result实现一对多映射 Collection</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Mybatis-plust%E6%96%B0%E7%89%B9%E6%80%A7%EF%BC%9A%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E5%99%A8"><span class="toc-number">10.</span> <span class="toc-text">
          Mybatis_plust新特性：代码生成器</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E9%9C%80%E8%A6%81%E7%9A%84%E6%8F%92%E4%BB%B6%EF%BC%88IDEA%E5%8F%B3%E4%BE%A7-MAVEN%E9%87%8C%E9%9D%A2%E7%9A%84%E6%8F%92%E4%BB%B6%E5%8F%8C%E5%87%BB%E5%90%AF%E5%8A%A8%EF%BC%89"><span class="toc-number">10.1.</span> <span class="toc-text">
          1.需要的插件（IDEA右侧 MAVEN里面的插件双击启动）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6-generatorConfig-xml"><span class="toc-number">10.2.</span> <span class="toc-text">
          2.配置文件 generatorConfig.xml</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Mybatis%E4%B8%AD%E5%87%BA%E7%8E%B0%E7%9A%84%E9%97%AE%E9%A2%98%EF%BC%9A"><span class="toc-number">11.</span> <span class="toc-text">
          Mybatis中出现的问题：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-UserMapper-xml%E5%88%B0%E5%BA%95%E5%BA%94%E8%AF%A5%E6%94%BE%E5%9C%A8%E9%82%A3%E9%87%8C%EF%BC%9F"><span class="toc-number">11.1.</span> <span class="toc-text">
          1.UserMapper.xml到底应该放在那里？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE%E5%AE%9E%E4%BD%93%E7%B1%BB%E5%BA%94%E8%AF%A5%E6%B3%A8%E6%84%8F%E7%9A%84%E9%97%AE%E9%A2%98"><span class="toc-number">11.2.</span> <span class="toc-text">
          配置实体类应该注意的问题</span></a></li></ol></li></ol></section><!-- ov = overview--><section class="sidebar-ov hide"><div class="sidebar-ov-author"><div class="sidebar-ov-author__avatar"><img class="sidebar-ov-author__avatar_img" src="/blog/images/avatar.jpg" alt="avatar"></div><p class="sidebar-ov-author__text">C'est la vie</p></div><div class="sidebar-ov-state"><a class="sidebar-ov-state-item sidebar-ov-state-item--posts" href="/blog/archives/"><div class="sidebar-ov-state-item__count">48</div><div class="sidebar-ov-state-item__name">归档</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--categories" href="/blog/categories/"><div class="sidebar-ov-state-item__count">19</div><div class="sidebar-ov-state-item__name">分类</div></a><a class="sidebar-ov-state-item sidebar-ov-state-item--tags" href="/blog/tags/"><div class="sidebar-ov-state-item__count">20</div><div class="sidebar-ov-state-item__name">标签</div></a></div><div class="sidebar-ov-cc"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en" target="_blank" rel="noopener" data-popover="知识共享许可协议" data-popover-pos="up"><img src="/blog/images/cc-by-nc-sa.svg"></a></div></section><div class="sidebar-reading"><div class="sidebar-reading-info"><span class="sidebar-reading-info__text">你已阅读了 </span><span class="sidebar-reading-info__num">0</span><span class="sidebar-reading-info__perc">%</span></div><div class="sidebar-reading-line"></div></div></aside></div><div class="clearfix"></div></div></main><footer class="footer" id="footer"><div class="footer-inner"><div><span>Copyright © 2021</span><span class="footer__icon"><i class="fas fa-heart"></i></span><span>何水浪</span></div><div><span>由 <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a> 强力驱动</span><span> v5.4.0</span><span class="footer__devider">|</span><span>主题 - <a href="https://github.com/liuyib/hexo-theme-stun/" title="Stun" target="_blank" rel="noopener">Stun</a></span><span> v2.6.2</span></div></div></footer><div class="loading-bar" id="loading-bar"><div class="loading-bar__progress"></div></div><div class="back2top" id="back2top"><span class="back2top__icon"><i class="fas fa-rocket"></i></span></div></div><div class="search-mask"></div><div class="search-popup"><span class="search-close"></span><div class="search-input"><input placeholder="搜索文章（支持多关键词，请用空格分隔）"></div><div class="search-results"></div></div><script src="https://cdn.jsdelivr.net/npm/jquery@v3.4.1/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.2/velocity.ui.min.js"></script><script>function initSearch() {
  var isXML = true;
  var search_path = 'search.json';

  if (!search_path) {
    search_path = 'search.xml';
  } else if (/json$/i.test(search_path)) {
    isXML = false;
  }

  var path = '/blog/' + search_path;
  $.ajax({
    url: path,
    dataType: isXML ? 'xml' : 'json',
    async: true,
    success: function (res) {
      var datas = isXML ? $('entry', res).map(function () {
        // 将 XML 转为 JSON
        return {
          title: $('title', this).text(),
          content: $('content', this).text(),
          url: $('url', this).text()
        };
      }).get() : res;
      var $input = $('.search-input input');
      var $result = $('.search-results');
      // 搜索对象（标题、内容）的权重，影响显示顺序
      var WEIGHT = { title: 100, content: 1 };
      var searchPost = function () {
        var searchText = $input.val().toLowerCase().trim();
        // 根据空白字符分隔关键字
        var keywords = searchText.split(/[\s]+/);
        // 搜索结果
        var matchPosts = [];

        // 有多个关键字时，将原文字整个保存下来
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        // 防止未输入字符时搜索
        if (searchText.length > 0) {
          datas.forEach(function (data) {
            var isMatch  = false;
            // 没有标题的文章使用预设的 i18n 变量代替
            var title = (data.title && data.title.trim()) || '[ 文章无标题 ]';
            var titleLower = title && title.toLowerCase();
            // 删除 HTML 标签 和 所有空白字符
            var content = data.content && data.content.replace(/<[^>]+>/g, '');
            var contentLower = content && content.toLowerCase();
            // 删除重复的 /
            var postURL = data.url && decodeURI(data.url).replace(/\/{2,}/g, '/');
            // 标题中匹配到的关键词
            var titleHitSlice = [];
            // 内容中匹配到的关键词
            var contentHitSlice = [];

            keywords.forEach(function (keyword) {
              /**
              * 获取匹配的关键词的索引
              * @param {String} keyword 要匹配的关键字
              * @param {String} text 原文字
              * @param {Boolean} caseSensitive 是否区分大小写
              * @param {Number} weight 匹配对象的权重。权重大的优先显示
              * @return {Array}
              */
              function getIndexByword (word, text, caseSensitive, weight) {
                if (!word || !text) {
                  return [];
                };

                var startIndex = 0; // 每次匹配的开始索引
                var index = -1;     // 匹配到的索引值
                var result = [];    // 匹配结果

                if (!caseSensitive) {
                  word = word.toLowerCase();
                  text = text.toLowerCase();
                }

                while((index = text.indexOf(word, startIndex)) !== -1) {
                  var hasMatch = false;
                  // 索引位置相同的关键词，保留长度较长的
                  titleHitSlice.forEach(function (hit) {
                    if (hit.index === index && hit.word.length < word.length) {
                      hit.word = word;
                      hasMatch = true;
                    }
                  });
                  startIndex = index + word.length;
                  !hasMatch && result.push({ index: index, word: word, weight: weight });
                }
                return result;
              }
              titleHitSlice = titleHitSlice.concat(getIndexByword(keyword, titleLower, false, WEIGHT.title));
              contentHitSlice = contentHitSlice.concat(getIndexByword(keyword, contentLower, false, WEIGHT.content));
            });

            var hitTitle = titleHitSlice.length;
            var hitContent = contentHitSlice.length;

            if (hitTitle > 0 || hitContent > 0) {
              isMatch = true;
            }
            if (isMatch) {
              ;[titleHitSlice, contentHitSlice].forEach(function (hit) {
                // 按照匹配文字的索引的递增顺序排序
                hit.sort(function (left, right) {
                  return left.index - right.index;
                });
              });
              /**
              * 给文本中匹配到的关键词添加标记，从而进行高亮显示
              * @param {String} text 原文本
              * @param {Array} hitSlice 匹配项的索引信息
              * @param {Number} start 开始索引
              * @param {Number} end 结束索引
              * @return {String}
              */
              function highlightKeyword (text, hitSlice, start, end) {
                if (!text || !hitSlice || !hitSlice.length) {
                  return;
                }

                var result = '';
                var startIndex = start;
                var endIndex = end;
                hitSlice.forEach(function (hit) {
                  if (hit.index < startIndex) {
                    return;
                  }

                  var hitWordEnd = hit.index + hit.word.length;
                  result += text.slice(startIndex, hit.index);
                  result += '<b>' + text.slice(hit.index, hitWordEnd) + '</b>';
                  startIndex = hitWordEnd;
                });
                result += text.slice(startIndex, endIndex);
                return result;
              }

              var postData = {};
              // 文章总的搜索权重
              var postWeight = titleHitSlice.length * WEIGHT.title + contentHitSlice.length * WEIGHT.content;
              // 标记匹配关键词后的标题
              var postTitle = highlightKeyword(title, titleHitSlice, 0, title.length) || title;
              // 标记匹配关键词后的内容
              var postContent;
              // 显示内容的长度
              var SHOW_WORD_LENGTH = 200;
              // 命中关键词前的字符显示长度
              var SHOW_WORD_FRONT_LENGTH = 20;
              var SHOW_WORD_END_LENGTH = SHOW_WORD_LENGTH - SHOW_WORD_FRONT_LENGTH;

              // 截取匹配的第一个字符，前后共 200 个字符来显示
              if (contentHitSlice.length > 0) {
                var firstIndex = contentHitSlice[0].index;
                var start = firstIndex > SHOW_WORD_FRONT_LENGTH ? firstIndex - SHOW_WORD_FRONT_LENGTH : 0;
                var end = firstIndex + SHOW_WORD_END_LENGTH;
                postContent = highlightKeyword(content, contentHitSlice, start, end);
              } else { // 未匹配到内容，直接截取前 200 个字符来显示
                postContent = content.slice(0, SHOW_WORD_LENGTH);
              }
              postData.title = postTitle;
              postData.content = postContent;
              postData.url = postURL;
              postData.weight = postWeight;
              matchPosts.push(postData);
            }
          });
        }

        var resultInnerHtml = '';
        if (matchPosts.length) {
          // 按权重递增的顺序排序，使权重大的优先显示
          matchPosts.sort(function (left, right) {
            return right.weight - left.weight;
          });
          resultInnerHtml += '<ul>';
          matchPosts.forEach(function (post) {
            resultInnerHtml += '<li><a class="search-results-title" href="' + post.url + '">';
            resultInnerHtml += post.title;
            resultInnerHtml += '</a><div class="search-results-content">';
            resultInnerHtml += post.content;
            resultInnerHtml += '</div></li>';
          });
          resultInnerHtml += '</ul>';
        } else {
          resultInnerHtml += '<div class="search-results-none"><i class="far fa-meh"></i></div>';
        }
        $result.html(resultInnerHtml);
      };
      $input.on('input', searchPost);
      $input.on('keyup', function (e) {
        if (e.keyCode === Stun.utils.codeToKeyCode('Enter')) {
          searchPost();
        }
      });
    }
  });
}

function closeSearch () {
  $('body').css({ overflow: 'auto' });
  $('.search-popup').css({ display: 'none' });
  $('.search-mask').css({ display: 'none' });
}

window.addEventListener('DOMContentLoaded', function () {
  Stun.utils.pjaxReloadLocalSearch = function () {
    $('.header-nav-search').on('click', function (e) {
      e.stopPropagation();
      $('body').css('overflow', 'hidden');
      $('.search-popup')
        .velocity('stop')
        .velocity('transition.expandIn', {
          duration: 300,
          complete: function () {
            $('.search-popup input').focus();
          }
        });
      $('.search-mask')
        .velocity('stop')
        .velocity('transition.fadeIn', {
          duration: 300
        });

      initSearch();
    });
    $('.search-mask, .search-close').on('click', function () {
      closeSearch();
    });
    $(document).on('keydown', function (e) {
      // Escape <=> 27
      if (e.keyCode === Stun.utils.codeToKeyCode('Escape')) {
        closeSearch();
      }
    });
  };

  Stun.utils.pjaxReloadLocalSearch();
}, false);

function safeOpenUrl(url) {
  var newTab = window.open();
  newTab.opener = null;
  newTab.location = url;
}

function extSearch(engine) {
  var engines = {
    google: 'https://www.google.com/search?q=',
    bing: 'https://cn.bing.com/search?q=',
    baidu: 'https://www.baidu.com/s?ie=UTF-8&wd=',
  };
  var host = window.location.host;
  var query = $('.search-input input').val().toLowerCase().trim();
  var uri = engines[engine] + query + ' site:' + host;

  if (query) {
    safeOpenUrl(uri);
  } else {
    Stun.utils.popAlert('warning', '请输入字符');
  }
}

var assistSearchList = window.CONFIG.assistSearch;

if (Array.isArray(assistSearchList)) {
  assistSearchList.forEach(function (name) {
    document.querySelector('.search-btns-item--' + name).addEventListener('click', function () {
      extSearch(name);
    }, false);
  });
}</script><script src="https://cdn.jsdelivr.net/npm/leancloud-storage@latest/dist/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine@latest/dist/Valine.min.js"></script><script>function loadValine () {
  var GUEST_INFO = ['nick', 'mail', 'link'];
  var guest_info = 'nick';

  guest_info = guest_info.split(',').filter(function(item) {
    return GUEST_INFO.indexOf(item) > -1;
  });
  new Valine({
    el: '#valine-container',
    appId: 'fJ4fFnieffDVKy4Jkn16aHdO-gzGzoHsz',
    appKey: 'qfVo2CUC2pJ3udFzLFnd0GBM',
    notify: true,
    verify: true,
    placeholder: '说点啥再走呗~爱你',
    avatar: 'mp',
    meta: guest_info,
    pageSize: '10' || 10,
    visitor: false,
    recordIP: false,
    lang: '' || 'zh-cn',
    path: window.location.pathname
  });
}

if (false) {
  loadValine();
} else {
  window.addEventListener('DOMContentLoaded', loadValine, false);
}</script><script src="/blog/js/utils.js?v=2.6.2"></script><script src="/blog/js/stun-boot.js?v=2.6.2"></script><script src="/blog/js/scroll.js?v=2.6.2"></script><script src="/blog/js/header.js?v=2.6.2"></script><script src="/blog/js/sidebar.js?v=2.6.2"></script><script type="application/json" src="/blog/search.json"></script></body></html>